package com.yisen.securitystudy.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        ObjectMapper objectMapper = new ObjectMapper();
        String authorization = request.getHeader("Authorization");
        String token = authorization.substring(7);
        String jsonStr = JwtHelper.decode(token).getClaims();
        System.out.println(jsonStr);
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(jsonStr);
//            jsonNode.
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonNode.get("msg").textValue();
    }
}
